package com.young.aspect;

import com.alibaba.fastjson.JSONObject;
import com.young.annot.Log;
import com.young.domain.SysLog;
import com.young.domain.SysUser;
import com.young.shop.service.SysLogService;
import java.lang.reflect.Method;
import java.util.Date;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Description: 新增系统日志的切面
 * @Author: kangyang
 * @Date: 2021/5/19 23:32
 **/
@Component
@Aspect
public class LogAspect {

  @Autowired
  private SysLogService sysLogService;

  @Around("@annotation(com.young.annot.Log)")
  public Object recordLog(ProceedingJoinPoint joinPoint) throws Throwable {
    SysLog sysLog = new SysLog();
    SysUser principal = (SysUser) SecurityUtils.getSubject().getPrincipal();
    sysLog.setUsername(principal.getUsername());
    MethodSignature signature = (MethodSignature) joinPoint.getSignature();
    Method method = signature.getMethod();
    String methodname = method.getName();
    sysLog.setMethod(methodname);
    Object target = joinPoint.getTarget();
    Method realMethod = null;
    try {
      realMethod = target.getClass().getMethod(methodname, method.getParameterTypes());
    } catch (NoSuchMethodException e) {
      e.printStackTrace();
    }
    Log annotation = realMethod.getAnnotation(Log.class);
    sysLog.setOperation(annotation.name());
    sysLog.setParams(JSONObject
        .toJSONString(joinPoint.getArgs() == null ? "param is null" : joinPoint.getArgs()));
    sysLog.setIp("127.0.0.1");
    long start = System.currentTimeMillis();
    Object proceed = null;
    proceed = joinPoint.proceed(joinPoint.getArgs());
    long end = System.currentTimeMillis();
    sysLog.setTime(end - start);
    sysLog.setCreateDate(new Date());
    sysLogService.saveSysLog(sysLog);
    return proceed;
  }

}
